package com.zqxq.file.service.impl;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.zqxq.file.config.SuffixContant;
import com.zqxq.file.service.IUploadFileService;
import com.zqxq.file.utils.MyThreadPoolExecutor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 永久保存有外链
 * http://attachmentpublic.s3.cn-north-1.amazonaws.com.cn/
 * Created by root on 15/11/7.
 */
@Slf4j
public abstract class UploadForAttachment implements IUploadFileService {
   /* private static  String S3_HTTP = "http://halorupiah-public.s3-ap-southeast-1.amazonaws.com/";
    private static  String S3_WRITE_ACCESS_KEY = "AKIAJ7GHBS3JGE57MPSA";
    private static  String S3_WRITE_SCERET_KEY = "/7QpH5fCUqsw94xEZ+ED1lJCuxKKL38u+VEv418R";
    private static  String S3_BUCKET_NAME = "halorupiah-public";*/
    public abstract String getS3Http();
    public abstract String getS3WriteAccessKey();
    public abstract String getS3BucketName();
    public abstract String getS3WriteSceretKey();
    public abstract String getKey(Object object,String fileSuff);
    /**
     * @param inputStream 输入流
     * @param contentType 内容类型
     * @param fileSuff    后缀名称
     * @return
     * @throws Exception
     */
    public String uploadToS3(InputStream inputStream, String contentType, String fileSuff) throws Exception {
        if (StringUtils.isEmpty(inputStream) || StringUtils.isEmpty(fileSuff)) {
            log.error("文件后缀不能为null");
            return "";
        }
        // 上传流
        ObjectMetadata metadata = new ObjectMetadata();
        // 根据扩展名判断图片格式
        metadata.setContentType(contentType);
        metadata.setContentLength(Long.valueOf(inputStream.available()));
        // 生成Key
        String key =getKey(null,fileSuff);
        upload(key, inputStream, metadata);
        String imgPath= getS3Http() + key;
        log.info("imgPath:-----------" + imgPath);
        return imgPath;
    }
    public String uploadToS3(InputStream inputStream, SuffixContant ss) throws Exception {
        if (StringUtils.isEmpty(inputStream) || StringUtils.isEmpty(ss)) {
            log.error("文件后缀不能为null");
            return "";
        }
        // 上传流
        ObjectMetadata metadata = new ObjectMetadata();
        // 根据扩展名判断图片格式
        String contentType = ss.getContentType();
        metadata.setContentType(contentType);
        metadata.setContentLength(Long.valueOf(inputStream.available()));
        // 生成Key
        String key =getKey(null,ss.getKey());
        upload(key, inputStream, metadata);
        String imgPath = getS3Http() + key;
        log.info("imgPath:-----------" + imgPath);
        return imgPath;
    }

    //上传文件
    public String uploadToS3(File tempFile, String fileSuff) throws Exception {
        if (StringUtils.isEmpty(tempFile)) {
            return "";
        }
        //定义返回值
        String imgPath = "";
        // 上传流
        ObjectMetadata metadata = new ObjectMetadata();
        InputStream inputStream = new FileInputStream(tempFile);
        String contentType = new MimetypesFileTypeMap().getContentType(tempFile);
        log.info("内容类型为：" + contentType);
        // 根据扩展名判断图片格式
        metadata.setContentType(contentType);
        metadata.setContentLength(Long.valueOf(inputStream.available()));
        // 生成Key
        String key = getKey(tempFile,fileSuff);
        upload(key, inputStream, metadata);
        imgPath= getS3Http() + key;
        log.info("imgPath:-----------" + imgPath);
        return imgPath;
    }

    /**
     * @param uploadFile
     * @param fileSuff   文件后缀 png/jpg等等 允许修改
     * @return
     * @throws Exception
     */
    public String uploadToS3(MultipartFile uploadFile, String appKey, String fileSuff) throws Exception {
        if (StringUtils.isEmpty(uploadFile)) {
            return "";
        }
        //定义返回值
        String imgPath = "";
        // 上传流
        ObjectMetadata metadata = new ObjectMetadata();
        InputStream inputStream = uploadFile.getInputStream();
        String fileType = uploadFile.getContentType();
        //获取key
        String key =appKey + "/" + getKey(uploadFile,fileSuff);
        // 根据扩展名判断图片格式
        metadata.setContentType(fileType);
        //inputStream.available()  --根据描述符获取输入文件的大小
        metadata.setContentLength(Long.valueOf(inputStream.available()));
        upload(key, inputStream, metadata);
        imgPath= getS3Http() + key;
        log.info("imgPath:-----------" + imgPath);
        return imgPath;
    }

    //上传
    public void upload(String key, InputStream inputStream, ObjectMetadata metadata) throws Exception {
        log.info("开始上传图片");
        MyThreadPoolExecutor.add(new Runnable() {
            @Override
            public void run() {
                try {
                    log.info("============getS3BucketName()=" + getS3BucketName());
                    AmazonS3 s3 = new AmazonS3Client(
                            new BasicAWSCredentials(getS3WriteAccessKey(), getS3WriteSceretKey()));
                    s3.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1));
                    s3.putObject(new PutObjectRequest(getS3BucketName(), key, inputStream, metadata));
                    log.info("=========URL=================" + key + "============URL=============");
                } catch (AmazonServiceException ase) {
                    ase.printStackTrace();
                    log.error("====================================AWS S3 UPLOAD ERROR START======================================");
                    log.error("Caught an AmazonServiceException, which means your request made it "
                            + "to Amazon S3, but was rejected with an error response for some reason.");
                    log.error("Caught an AmazonServiceException, which means your request made it "
                            + "to Amazon S3, but was rejected with an error response for some reason.");
                    log.error("Error Message:    " + ase.getMessage());
                    log.error("HTTP Status Code: " + ase.getStatusCode());
                    log.error("AWS Error Code:   " + ase.getErrorCode());
                    log.error("Error Type:       " + ase.getErrorType());
                    log.error("Request ID:       " + ase.getRequestId());
                    log.error(ase.getMessage());
                    log.error("====================================AWS S3 UPLOAD ERROR END======================================");
                } catch (AmazonClientException ace) {
                    log.error("====================================AWS S3 UPLOAD ERROR START======================================");
                    log.error("Caught an AmazonClientException, which means the client encountered "
                            + "a serious internal problem while trying to communicate with S3, "
                            + "such as not being able to access the network.");
                    log.error("Error Message: " + ace.getMessage());
                    log.error("====================================AWS S3 UPLOAD ERROR END======================================");
                } finally {
                    if (!StringUtils.isEmpty(inputStream)) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    public static void main(String[] args) {
        try {
            InputStream test=new FileInputStream("C:/Users/ZQXQ/Pictures/Saved Pictures/test.png");
            String s=  new UploadFileServiceImplPublic().uploadToS3(new File("C:/Users/ZQXQ/Pictures/Saved Pictures/test.png"),"");
           log.error(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
